{extend name="common:base" /}

{block name="page_title"}编辑{$controllerName} 修改【{$model['goods_name']}】{/block}
{block name="style"}
<link href="https://cdn.staticfile.org/pretty-checkbox/3.0.3/pretty-checkbox.min.css" rel="stylesheet">
<link href="https://cdn.staticfile.org/select2/4.0.5/css/select2.min.css" rel="stylesheet">
<style>
    .select2-container--default .select2-selection--multiple .select2-selection__choice{background-color:#3c8dbc;border-color:#367fa9;padding: 1px 10px;color: #fff;}
    .select2-container--default .select2-selection--multiple .select2-selection__choice__remove{margin-right:5px;color:rgba(255,255,255,0.7);}
    .form-group .region-goods-right .table-bordered{border: 1px solid #ddd;}
    .table > thead > tr > td.full, .table > tbody > tr > td.full, .table > tfoot > tr > td.full {
        white-space: normal;
        line-height: 20px;
        vertical-align: middle;
    }
    .table {
        table-layout: fixed;
        position: relative;
        color: #666;
    }
    .input-group-addon .pretty{margin-right:0;}
</style>
{/block}
{block name="content"}
<div class="box">
    <div class="box-header with-border">
        <ul class="nav nav-tabs" role="tablist" id="myTabs">
            <li role="presentation"><a href="#basic" aria-controls="basic" role="tab" data-toggle="tab">基本</a></li>
            <li role="presentation"><a href="#option" aria-controls="option" role="tab" data-toggle="tab">价格/规格</a></li>
            <li role="presentation"><a href="#des" aria-controls="des" role="tab" data-toggle="tab">详情</a></li>
        </ul>
    </div>
    <form class="form-horizontal ajaxFormGoods" name="form0" method="post" action="{:url('')}">
        <input type="hidden" name="id" value="{model:safe_show field='id' /}">
        <div class="box-body">
            <div class="tab-content">
                <div role="tabpanel" class="tab-pane" id="basic">
                    {include file="goods/goods_basic" /}
                </div>
                <div role="tabpanel" class="tab-pane" id="option">
                    {include file="goods/goods_option" /}
                </div>
                <div role="tabpanel" class="tab-pane" id="des">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">商品详情</label>
                        <div class="col-sm-8">
                            <textarea type="text" name="goods_content" class="form-control nd-umeditor" id="umeditor_goods_content">{model:safe_show field='goods_content' /}</textarea>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- /.box-body -->
        <div class="box-footer">
            <div class="row">
                <div class="col-xs-2"></div>
                <div class="col-xs-10">
                    <button type="submit" class="btn btn-info ladda-button" data-style="expand-left" data-plugin="ladda">
                        <span class="ladda-label"><i class="icon wb-arrow-expand margin-right-10" aria-hidden="true"></i>提交</span>
                    </button>
                    <a href="{:url('index')}" class="btn btn-default">返回列表</a>
                </div>
            </div>
        </div>
        <!-- /.box-footer -->
        <textarea name="options" id="h_options" style="display:none;"></textarea>
        <textarea name="specs" id="h_specs" style="display:none;"></textarea>
    </form>
</div>
{/block}

{block name="script"}
<script src="https://cdn.staticfile.org/select2/4.0.5/js/select2.min.js"></script>
<script src="https://cdn.staticfile.org/Vue.Draggable/2.16.0/vuedraggable.js"></script>
<script>
    var tabContentLoadFn = {
        'basic' : function () {
            $('.select2-multiple').select2();
        }
        ,'option' : function () {

        }
        ,'des' : function () {
            if(false == isLoad_umeditor_goods_content){
                fn_umeditor_goods_content();
            }
        }
    };
    $(document).ready(function() {
        $('#myTabs a').click(function (e) {
            e.preventDefault()
            $(this).tab('show')
            var tabName = $(this).attr('aria-controls');
            if('function' == typeof tabContentLoadFn[tabName]){
                tabContentLoadFn[tabName]();
                // 方法执行完后空置方法
                setTimeout(function () {
                    tabContentLoadFn[tabName] = false;
                },2000);
            }
        });
        // 默认选中第一个tab
        setTimeout(function () {
            $('#myTabs a:first').click();
        })
    });
</script>
<script>
    var isLoad_umeditor_goods_content = false;
    var fn_umeditor_goods_content = function () {
        if(!window['gdbase']){
            console.log('等待加载...');
            setTimeout(fn_umeditor_goods_content,500);
            return;
        }
        gdbase.initUmEditor('.nd-umeditor');
        isLoad_umeditor_goods_content = true;
    }
</script>
<script>
    gdbase.uploadMultiImages({inputName:"thumbs",elm:".multi-img-box-thumbs",multi:1});
</script>
{if (empty($model['has_option']))}
<script>
    var model_specs = [];
    var model_inputs = [];
    var model_one_inputs = {:json_encode($model['options'][0],256)};
</script>
{else /}
<script>
    var model_specs = {:json_encode($model['specs'],256)};
    var model_inputs = {:json_encode($model['options'],256)};
    var model_one_inputs = [];
</script>
{/if}
<script>
    var app = new Vue({
        el: '#app',
        data: {
            specs:model_specs
            ,specItemFieldShowName:'title'  //属性列需要显示的列名
            ,inputs:[]  // 规格
            ,one_input:model_one_inputs  // 单个规格
            ,dragging: false
            ,has_option: {model:safe_show field='has_option' default='false' /}
            ,stock: {model:safe_show field='stock' default='999' /}
            ,batchInput:{
                'option_stock':''
                ,'option_marketprice':''
                ,'option_productprice':''
                ,'option_costprice':''
                ,'option_goodssn':''
                ,'option_productsn':''
                ,'option_weight':''
            }
        }
        ,
        methods:{
            addSpec:function () {
                if(this.specs.length < 5){
                    this.specs.push({
                        'title':''
                        ,'items':[]
                    })
                }
            }
            ,
            delSpec:function (_index) {
                if (confirm('确认要删除此规格?')){
                    this.specs.splice(_index,1)
                }
            }
            ,
            addSpecItem:function (_spec) {
                _spec.items.push({
                    'title':''
                    ,'show':true
                })
            }
            ,
            delSpecItem:function (_spec,_index) {
                _spec.items.splice(_index,1)
            }
            ,
            /*
              计算属性的乘积
              @params
                specIndex 规格项目在 advancedSpecification 中的序号
            */
            countSum :function(specIndex) {
                var num = 1
                this.specs.forEach((item, index) => {
                    if (index >= specIndex && item.items.length) {
                        num *= item.items.length
                    }
                })
                return num
            }
            ,
            /*
              根据传入的属性值，拿到相应规格的属性
              @params
                specIndex 规格项目在 advancedSpecification 中的序号
                index 所有属性在遍历时的序号
            */
            getSpecAttr :function(specIndex, index) {
                var _this = this;
                // 获取当前规格项目下的属性值
                var currentValues = _this.specs[specIndex].items
                var indexCopy

                // 判断是否是最后一个规格项目
                if (_this.specs[specIndex + 1] && _this.specs[specIndex + 1].items.length) {
                    indexCopy = index / _this.countSum(specIndex + 1)
                } else {
                    indexCopy = index
                }

                var i = indexCopy % currentValues.length
                if (i.toString() !== 'NaN' && i % 1 === 0) {
                    return currentValues[i][_this.specItemFieldShowName]
                } else {
                    return ''
                }
            }
            ,
            // 根据传入的条件，来判断是否显示该td
            showTd (specIndex, index) {
                // 如果当前项目下没有属性，则不显示
                if (!this.specs[specIndex]) {
                    return false

                    // 自己悟一下吧
                } else if (index % this.countSum(specIndex + 1) === 0) {
                    return true
                } else {
                    return false
                }
            }
            ,
            /**
             *  规格2 不进行单元格合并
             */
            getSpecAttr2 :function(specIndex, index , _field) {
                var _this = this;
                // 获取当前规格项目下的属性值
                var currentValues = _this.specs[specIndex].items
                var indexCopy

                // 判断是否是最后一个规格项目
                if (_this.specs[specIndex + 1] && _this.specs[specIndex + 1].items.length) {
                    indexCopy = index / _this.countSum(specIndex + 1)
                } else {
                    indexCopy = index
                }

                var i = Math.floor(indexCopy % currentValues.length)

                if (i.toString() !== 'NaN') {
                    if(!_field || !currentValues[i][_field]){
                        return currentValues[i][_this.specItemFieldShowName]
                    }
                    else{
                        return currentValues[i][_field]
                    }
                } else {
                    return ''
                }
            }
            ,
            /**
             *  获取spec里面的下标
             */
            getSpecItemIndex :function(specIndex, index) {
                var _this = this;
                // 获取当前规格项目下的属性值
                var currentValues = _this.specs[specIndex].items
                var indexCopy

                // 判断是否是最后一个规格项目
                if (_this.specs[specIndex + 1] && _this.specs[specIndex + 1].items.length) {
                    indexCopy = index / _this.countSum(specIndex + 1)
                } else {
                    indexCopy = index
                }

                var i = Math.floor(indexCopy % currentValues.length)

                if (i.toString() !== 'NaN') {
                    return i;
                } else {
                    return -1;
                }
            }
            ,
            /**
             * 刷新规格
             */
            refreshOptions:function () {
                var _this = this;
                var len = _this.countSum(0)
                var tmpInputs = [];
                for (var i = 0; i < len; i++ ){
                    var tmp = {'item':[]};
                    _this.specs.forEach((item, specIndex) => {
                        tmp['item'].push({
                            'title':_this.getSpecAttr2(specIndex, i)
                            ,'index':specIndex + '_' + _this.getSpecItemIndex(specIndex, i)
                        })
                    })
                    //插入其他输入框
                    tmpInputs.push(_this.insertOtherInput(tmp,i));
                }
                _this.inputs = tmpInputs;
            }
            ,
            /**
             * 插入其他输入框
             */
            insertOtherInput:function (_row,_index) {
                var tmp = model_inputs[_index];
                if (tmp) {
                    return $.extend({}, _row, tmp);
                }
                else{
                    _row['id'] = '';
                    _row['option_stock'] = '';
                    _row['option_marketprice'] = '';
                    _row['option_productprice'] = '';
                    _row['option_costprice'] = '';
                    _row['option_goodssn'] = '';
                    _row['option_productsn'] = '';
                    _row['option_weight'] = '';
                    return _row;
                }
            }
            ,
            setCol:function (_field) {
                var _this = this;
                _this.inputs.forEach((item, specIndex) => {
                    item[_field] = _this.batchInput[_field]
                })
            }
        }
        ,
        mounted:function () {
            this.refreshOptions()
        }
    })
</script>
<script>
    $(".ajaxFormGoods").submit(function(){
        // 组织规格

        if(app.has_option){
            $('#h_options').html(JSON.stringify(app.inputs));
            $('#h_specs').html(JSON.stringify(app.specs));
        }

        $(this).ajaxSubmit({
            success:complete3
        });
        return false;
    });
</script>
{/block}